import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI

from src.config.application import applicationConfig
from src.config.logger import logging_config
from src.controllers import index_router, member_router, task_router
from src.resource.database import create_db_and_tables_async
from src.utils.function import app_path, src_path, static_path, logging_path
from src.utils.rs import Rs

# +-------------------
# + 项目根目录
# +-------------------
APP_ABS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))


# +-------------------
# + lifespan
# +-------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
    print("🚀 应用启动，初始化资源...")
    # 异步创建数据库表
    # await create_db_and_tables_async()
    print("✅ 数据库表初始化完成")
    yield
    print("🛑 应用关闭，清理资源...")


# +-------------------
# + 配置日志
# +-------------------
logging_config(os.path.join(APP_ABS_PATH, "logs"))
logger = logging.getLogger("uvicorn")

# +-------------------
# + FastAPI
# +-------------------
app = FastAPI(
    lifespan=lifespan,
    title=applicationConfig.TITLE,
    description=applicationConfig.DESCRIPTION,
    version=applicationConfig.VERSION,
)

# +-------------------
# + 路由
# +-------------------
app.include_router(index_router)
app.include_router(member_router)
app.include_router(task_router)
